package com.hxk.jwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.hxk.jwt.annotation.PassToken;
import com.hxk.jwt.annotation.UserLoginToken;
import com.hxk.jwt.entity.User;
import com.hxk.jwt.service.TokenService;
import com.hxk.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JwtController {


    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    //登录
    @PassToken
    @PostMapping("/login")
    public Object login(User user){
        JSONObject jsonObject=new JSONObject();
        User userForBase=userService.findByUsername(user);
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!userForBase.getPassword().equals(user.getPassword())){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                String token = tokenService.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }


    /**
     * 该方法必须通过认证后才可以访问
     * @return
     */
    @UserLoginToken
    @GetMapping("/msg")
    public String getMsg(){
        return "通过认证";
    }
}
